{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "FLAGS = None\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们在这里调用系统提供的Mnist数据函数为我们读入数据，如果没有下载的话则进行下载。\n",
    "\n",
    "<font color=#ff0000>**这里将data_dir改为适合你的运行环境的目录**</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting /home/pxt/datasets/MNIST/train-images-idx3-ubyte.gz\n",
      "Extracting /home/pxt/datasets/MNIST/train-labels-idx1-ubyte.gz\n",
      "Extracting /home/pxt/datasets/MNIST/t10k-images-idx3-ubyte.gz\n",
      "Extracting /home/pxt/datasets/MNIST/t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = '/home/pxt/datasets/MNIST'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "声明x，y，学习率的占位符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create the model\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "learning_rate = tf.placeholder(tf.float32)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "变换输入图像"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [],
   "source": [
    "with tf.name_scope('reshape'):\n",
    "  x_image = tf.reshape(x, [-1, 28, 28, 1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "网络模型的构建"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [],
   "source": [
    "with tf.name_scope('conv1'):\n",
    "  h_conv1 = tf.layers.conv2d(x_image, 32, [5,5],\n",
    "                             padding='SAME',\n",
    "                             activation=tf.nn.relu)\n",
    " \n",
    "\n",
    "# Pooling layer - downsamples by 2X.\n",
    "with tf.name_scope('pool1'):\n",
    "  h_pool1 = tf.layers.max_pooling2d(h_conv1, pool_size=[2,2],\n",
    "                        strides=[2, 2], padding='VALID')\n",
    "\n",
    "# Second convolutional layer -- maps 32 feature maps to 64.\n",
    "with tf.name_scope('conv2'):\n",
    "  h_conv2 = tf.layers.conv2d(h_pool1, 64, [5,5],\n",
    "                             padding='SAME',\n",
    "                             activation=tf.nn.relu)\n",
    "\n",
    "# Second pooling layer.\n",
    "with tf.name_scope('pool2'):\n",
    "  h_pool2 = tf.layers.max_pooling2d(h_conv2, pool_size=[2,2],\n",
    "                        strides=[2, 2], padding='VALID')\n",
    "\n",
    "# Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image\n",
    "# is down to 7x7x64 feature maps -- maps this to 1024 features.\n",
    "with tf.name_scope('fc1'):\n",
    "  h_pool2_flat = tf.layers.flatten(h_pool2)\n",
    "  h_fc1 = tf.layers.dense(h_pool2_flat, 1024, activation=tf.nn.relu)\n",
    "\n",
    "# Dropout - controls the complexity of the model, prevents co-adaptation of\n",
    "# features.\n",
    "with tf.name_scope('dropout'):\n",
    "  keep_prob = tf.placeholder(tf.float32)\n",
    "  h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n",
    "\n",
    "# Map the 1024 features to 10 classes, one for each digit\n",
    "with tf.name_scope('fc2'):\n",
    "  y = tf.layers.dense(h_fc1_drop, 10, activation=None)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义损失函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [],
   "source": [
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为损失函数增加l2正则，选择优化器，进行全局初始化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [],
   "source": [
    "l2_loss = tf.add_n( [tf.nn.l2_loss(w) for w in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)] )\n",
    "total_loss = cross_entropy + 1e-3*l2_loss\n",
    "train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "开始训练模型，并输出在训练集上的损失函数值以及测试精度"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step 500, entropy loss: 0.354543, l2_loss: 7170.349121, total loss: 7.524893\n",
      "0.95\n",
      "step 1000, entropy loss: 0.144239, l2_loss: 7101.080566, total loss: 7.245320\n",
      "0.93\n",
      "0.9281\n",
      "step 1500, entropy loss: 0.180121, l2_loss: 7031.888184, total loss: 7.212009\n",
      "0.97\n",
      "step 2000, entropy loss: 0.141295, l2_loss: 6963.206543, total loss: 7.104501\n",
      "0.97\n",
      "0.958\n",
      "step 2500, entropy loss: 0.071451, l2_loss: 6895.014160, total loss: 6.966465\n",
      "0.98\n",
      "step 3000, entropy loss: 0.164250, l2_loss: 6827.395020, total loss: 6.991646\n",
      "0.94\n",
      "0.9663\n",
      "step 3500, entropy loss: 0.064687, l2_loss: 6760.364258, total loss: 6.825052\n",
      "0.98\n",
      "step 4000, entropy loss: 0.108054, l2_loss: 6693.919922, total loss: 6.801974\n",
      "0.99\n",
      "0.9713\n",
      "step 4500, entropy loss: 0.063174, l2_loss: 6628.089355, total loss: 6.691264\n",
      "0.97\n",
      "step 5000, entropy loss: 0.124518, l2_loss: 6562.866699, total loss: 6.687386\n",
      "0.98\n",
      "0.9755\n",
      "step 5500, entropy loss: 0.110408, l2_loss: 6498.233887, total loss: 6.608643\n",
      "1.0\n",
      "step 6000, entropy loss: 0.035860, l2_loss: 6434.240723, total loss: 6.470101\n",
      "0.99\n",
      "0.9765\n",
      "step 6500, entropy loss: 0.118507, l2_loss: 6370.819824, total loss: 6.489327\n",
      "0.98\n",
      "step 7000, entropy loss: 0.031227, l2_loss: 6308.031250, total loss: 6.339259\n",
      "1.0\n",
      "0.9802\n",
      "step 7500, entropy loss: 0.151152, l2_loss: 6245.848633, total loss: 6.397001\n",
      "0.96\n",
      "step 8000, entropy loss: 0.051736, l2_loss: 6184.257812, total loss: 6.235994\n",
      "1.0\n",
      "0.9811\n",
      "step 8500, entropy loss: 0.094082, l2_loss: 6123.277832, total loss: 6.217360\n",
      "0.96\n",
      "step 9000, entropy loss: 0.074464, l2_loss: 6062.877930, total loss: 6.137342\n",
      "1.0\n",
      "0.9812\n",
      "step 9500, entropy loss: 0.027997, l2_loss: 6003.071777, total loss: 6.031069\n",
      "1.0\n",
      "step 10000, entropy loss: 0.068840, l2_loss: 5943.822266, total loss: 6.012663\n",
      "0.99\n",
      "0.9809\n"
     ]
    }
   ],
   "source": [
    "for step in range(10000):\n",
    "  batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "  lr = 0.01\n",
    "  _, loss, l2_loss_value, total_loss_value = sess.run(\n",
    "               [train_step, cross_entropy, l2_loss, total_loss], \n",
    "               feed_dict={x: batch_xs, y_: batch_ys, learning_rate:lr, keep_prob:0.5})\n",
    "  \n",
    "  if (step+1) % 500 == 0:\n",
    "    print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "            (step+1, loss, l2_loss_value, total_loss_value))\n",
    "    # Test trained model\n",
    "    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    print(sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob:0.5}))\n",
    "  if (step+1) % 1000 == 0:\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                    y_: mnist.test.labels, keep_prob:0.5}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "毫无疑问，这个模型是一个非常简陋，性能也不理想的模型。目前只能达到92%左右的准确率。\n",
    "接下来，希望大家利用现有的知识，将这个模型优化至98%以上的准确率。\n",
    "Hint：\n",
    "- 卷积\n",
    "- 池化\n",
    "- 激活函数\n",
    "- 正则化\n",
    "- 初始化\n",
    "- 摸索一下各个超参数\n",
    "  - 卷积kernel size\n",
    "  - 卷积kernel 数量\n",
    "  - 学习率\n",
    "  - 正则化惩罚因子\n",
    "  - 最好每隔几个step就对loss、accuracy等等进行一次输出，这样才能有根据地进行调整"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
